iT邦幫忙

2023 iThome 鐵人賽

DAY 4
0
自我挑戰組

30天leetcode學習旅程系列 第 4

項次4 - Stacks -2

  • 分享至 

  • xImage
  •  

題目:20. Valid Parentheses

連結:https://leetcode.com/problems/valid-parentheses/description/

  • 等級:Easy

解題思路

  1. 利用stack紀錄括號起始與結束順序做比對
class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0 ; i < s.length();i++)
        {
            char c = s.charAt(i);
            if (c == '(')
                stack.push(')');
            else if (c == '{')
                stack.push('}');
            else if (c == '[')
                stack.push(']');
            else if (stack.isEmpty() || stack.pop() != c)
                return false;
        }
        if (stack.isEmpty())
            return true;
        else
            return false;
    }
}
  • Time complexity: O(n)
  • Space complexity: O(n)

題目:155. Min Stack

連結:https://leetcode.com/problems/valid-parentheses/description/

  • 等級:Medium

解題思路

  1. 利用stack並重新撰寫類別,而外而外紀錄最小值
  2. 當push和pop時,如果為最小值要額外push和pop
class MinStack {

    private Stack<Integer> stack;
    private int min = Integer.MAX_VALUE;

    public MinStack() {
        stack = new Stack<Integer>();
    }
    
    public void push(int val) {      
        if (val <= min)
        {
            stack.push(min);
            min = val;
        }
        stack.push(val);
    }
    
    public void pop() {
        if (stack.pop() == min)
            min = stack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return min;
    }
}
  • Time complexity: O(1)
  • Space complexity: O(n)

上一篇
項次3 - Stacks-1
下一篇
項次5 - Singly Linked List
系列文
30天leetcode學習旅程30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言